package com.thinkit.bigdata.web.controller.config;

import com.thinkit.bigdata.core.feature.orm.mybatis.Page;
import com.thinkit.bigdata.core.util.StringUtil;
import com.thinkit.bigdata.web.model.config.SysResource;
import com.thinkit.bigdata.web.model.config.SysResourceExample;
import com.thinkit.bigdata.web.model.result.ConfigResult;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.service.config.ResourceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Created by lihongli on 2018/9/1
 */
@Controller
@RequestMapping("resource")
public class ResourceController {

    private static Logger logger = Logger.getLogger(ResourceController.class);

    @Resource
    private ResourceService resourceService;

    /**
     * 进入资源配置页面
     *
     * @return
     */
    @RequestMapping(value = "/resources", method = RequestMethod.GET)
    public String showResources(HttpServletRequest request) {
        logger.info("进入资源配置页面");
        return "ConfigViews/resource";
    }

    /**
     * 分页查询配置信息
     *
     * @param request
     * @param sortOrder 排序方式
     * @param sortName  排序列名
     * @param pageNum   页码
     * @param pageSize  每页显示数量
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/resourcesByPage", method = RequestMethod.POST)
    public Page<SysResource> resourcesByPage(
            HttpServletRequest request,
            @RequestParam(value = "sortOrder") String sortOrder,
            @RequestParam(value = "sortName") String sortName,
            @RequestParam(value = "parentId", required = false) List<Long> parentId,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        String name = request.getParameter("name");
        String code = request.getParameter("code");
        String logTxt = "【资源配置分页查询】";
        logger.info(logTxt + "查询条件: pageNum=" + pageNum);
        logger.info(logTxt + "查询条件: pageSize=" + pageSize);
        logger.info(logTxt + "查询条件: parentId=" + StringUtils.join(parentId, ","));
        logger.info(logTxt + "查询条件: name=" + name);
        logger.info(logTxt + "查询条件: code=" + code);
        // 查询条件设置
        SysResourceExample example = new SysResourceExample();
        SysResourceExample.Criteria criteria = example.createCriteria();
        if (parentId != null && !parentId.isEmpty()) {
            criteria.andParentidIn(parentId);
        }
        if (StringUtil.isNotEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (StringUtil.isNotEmpty(code)) {
            criteria.andCodeLike("%" + code + "%");
        }
        // 排序方式设置
        example.setOrderByClause(sortName + " " + sortOrder);
        // 分页设置
        Page<SysResource> page = new Page<>(pageNum, pageSize);
        resourceService.selectByExample(page, example);
        logger.info(logTxt + "共计查询到" + page.getResult().size() + "条资源信息");
        return page;
    }

    /**
     * 添加资源
     *
     * @param resource
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/resourceAdd", method = RequestMethod.POST)
    public ConfigResult resourceAdd(HttpServletRequest request, SysResource resource) {
        String logTxt = "【资源新增】";
        logger.info(logTxt + "新增资源信息" + resource.toString());
        // 获取当前登录用户信息
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
        // 设置创建者信息 同时初始化修改者信息
        resource.setCreateuserid(user.getId());
        resource.setLastupdateuserid(user.getId());
        resource.setLastupdatetime(new Date());
        // 添加
        try {
            int rowNum = resourceService.insert(resource);
            if (rowNum > 0) {
                logger.info(logTxt + "数据库成功插入" + rowNum + "条数据");
                return new ConfigResult(Constants.SUCCESS, "资源添加成功");
            } else {
                logger.info(logTxt + "资源添加失败");
                return new ConfigResult(Constants.FAIL, "资源添加失败");
            }
        } catch (Exception e) {
            logger.error(logTxt + "资源添加错误", e);
            return new ConfigResult(Constants.ERROR, "资源添加错误");
        }
    }

    /**
     * 根据主键获取资源
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/resourceGetByPK")
    public SysResource resourceGetByPK(HttpServletRequest request, Long id) {
        logger.info("获取id为【" + id + "】的资源信息");
        return resourceService.resourceGetByPK(id);
    }

    /**
     * 页面选取父级资源，获取所有type为菜单/功能的信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/parentResourceAll", method = RequestMethod.GET)
    public List<SysResource> parentResourceAll(HttpServletRequest request) {
        logger.info("页面选取父级资源，获取所有type为菜单/功能的信息");
        SysResourceExample example = new SysResourceExample();
        example.createCriteria().andTypeNotEqualTo(2);
        return resourceService.parentResourceAll(example);
    }

    /**
     * 修改资源信息
     *
     * @param request
     * @param resource
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/resourceUpdate", method = RequestMethod.POST)
    public ConfigResult resourceUpdate(HttpServletRequest request, SysResource resource) {
        String logTxt = "【修改资源】";
        logger.info(logTxt + resource.toString());
        // 获取登录者信息 并设置修改信息
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
        resource.setLastupdateuserid(user.getId());
        resource.setLastupdatetime(new Date());
        try {
            int rowNum = resourceService.update(resource);
            if (rowNum > 0) {
                logger.info(logTxt + "数据库成功修改" + rowNum + "条数据");
                return new ConfigResult(Constants.SUCCESS, "资源修改成功");
            } else {
                logger.info(logTxt + "资源修改失败");
                return new ConfigResult(Constants.FAIL, "资源修改失败");
            }
        } catch (Exception e) {
            logger.error(logTxt + "资源修改错误", e);
            return new ConfigResult(Constants.ERROR, "资源修改错误");
        }
    }

    /**
     * 根据id删除对应的resource（本身以及所有下级资源）
     * （暂时未使用）
     *
     * @param request
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/resourceDelete")
    public ConfigResult resourceDelete(HttpServletRequest request, @RequestParam("id") Long id) {
        String logTxt = "【删除资源】";
        logger.info(logTxt + "删除id为" + id + "的资源信息");
        try {
            int rowNum = resourceService.resourceDelete(id);
            if (rowNum > 0) {
                // 因为是递归删除 实际删除数量大于等于rowNum
                logger.info(logTxt + "资源成功删除" + rowNum + "条");
                return new ConfigResult(Constants.SUCCESS, "资源成功删除");
            } else {
                logger.info(logTxt + "资源删除失败");
                return new ConfigResult(Constants.FAIL, "资源删除失败");
            }
        } catch (Exception e) {
            logger.error(logTxt + "资源删除错误", e);
            return new ConfigResult(Constants.ERROR, "资源删除错误");
        }
    }

    /**
     * 批量删除资源信息
     *
     * @param request
     * @param idList
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/resourceDeleteBatch", method = RequestMethod.POST)
    public ConfigResult resourceDeleteBatch(HttpServletRequest request, @RequestParam("idList") List<Long> idList) {
        String logTxt = "【资源批量删除】";
        logger.info(logTxt + "要删除的资源数量为：" + idList.size());
        if (!idList.isEmpty()) {
            try {
                int rowNum = resourceService.resourceDeleteBatch(idList);
                if (rowNum > 0) {
                    logger.info(logTxt + "资源批量删除" + rowNum + "条");
                    return new ConfigResult(Constants.SUCCESS, "批量删除成功");
                } else {
                    logger.info(logTxt + "资源批量删除失败");
                    return new ConfigResult(Constants.FAIL, "批量删除失败");
                }
            } catch (Exception e) {
                logger.error(logTxt + "资源批量删除错误", e);
                return new ConfigResult(Constants.ERROR, "批量删除错误");
            }
        } else {
            logger.info(logTxt + "未选择要删除的资源");
            return new ConfigResult(Constants.WARNING, "未选择要删除的资源");
        }
    }

    /**
     * 单个启用/停用
     *
     * @param request
     * @param id
     * @param status
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/statusSingle", method = RequestMethod.POST)
    public ConfigResult statusSingle(HttpServletRequest request, @RequestParam("id") Long id, @RequestParam("status") Integer status) {
        // 判断操作类型是启用还是停用
        String opType = Constants.getStatusName(status);
        String logTxt = "【资源" + opType + "】";
        logger.info(logTxt + "修改的资源id为：" + id);
        // 设置修改值
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
        SysResource resource = new SysResource();
        resource.setStatus(status);
        resource.setLastupdatetime(new Date());
        resource.setLastupdateuserid(user.getId());
        try {
            int rowNum = resourceService.statusSingle(resource, id);
            if (rowNum > 0) {
                logger.info(logTxt + "成功修改" + rowNum + "条资源的状态");
                return new ConfigResult(Constants.SUCCESS, "资源状态修改成功");
            } else {
                logger.info(logTxt + "状态修改失败");
                return new ConfigResult(Constants.FAIL, "资源状态修改失败");
            }
        } catch (Exception e) {
            logger.error(logTxt + "状态修改错误", e);
            return new ConfigResult(Constants.ERROR, "资源状态修改错误");
        }
    }

    /**
     * 批量启用/停用
     *
     * @param request
     * @param idList
     * @param status
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/statusBatch", method = RequestMethod.POST)
    public ConfigResult statusBatch(HttpServletRequest request, @RequestParam("idList") List<Long> idList, @RequestParam("status") Integer status) {
        // 判断操作类型是启用还是停用
        String opType = Constants.getStatusName(status);
        String logTxt = "【资源批量" + opType + "】";
        logger.info(logTxt + "批量修改的资源数量为：" + idList.size());
        if (!idList.isEmpty()) {
            // 设置修改值
            User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
            SysResource resource = new SysResource();
            resource.setStatus(status);
            resource.setLastupdatetime(new Date());
            resource.setLastupdateuserid(user.getId());
            try {
                int rowNum = resourceService.statusBatch(resource, idList);
                if (rowNum > 0) {
                    logger.info(logTxt + "成功修改" + rowNum + "条资源的状态");
                    return new ConfigResult(Constants.SUCCESS, "资源状态批量修改成功");
                } else {
                    logger.info(logTxt + "状态修改失败");
                    return new ConfigResult(Constants.FAIL, "资源状态批量修改失败");
                }
            } catch (Exception e) {
                logger.error(logTxt + "状态修改错误", e);
                return new ConfigResult(Constants.ERROR, "资源状态批量修改错误");
            }
        } else {
            logger.info(logTxt + "未选择要修改的资源");
            return new ConfigResult(Constants.WARNING, "未选择要修改的资源");
        }
    }
}
